<?php

namespace app\admin\controller;

use think\Db;

class Login extends Base
{
	public $admin;
	public function _initialize()
	{
		$this->checkLogin();
		$this->admin = session('admin');
	}
	 
	public function index() 
	{
		if ($this->request->isGet()) {
			$this->assign("title","用户登录");
			return $this->fetch();
		}
		else 
		{
			$captcha = input('verify');
			if(!captcha_check($captcha))
			{
 				//验证失败
 				showMsg("验证码错误","index");
            }

			if (!input("adminname") || !input("adminpwd")) {
				//$this->error("用户名和密码必填","index");
				//$this->error('新增失败');
				showMsg("用户名和密码必填","index");
			}

			$username = $this->request->post('adminname', '', 'trim');
			$password = md5($this->request->post('adminpwd', '', 'trim'));
			
			$admin = Db::name('sys_admin')->where('admin_name', $username)->find();
			  
			if(empty($admin) || $admin['admin_pwd'] !== $password)
			{
				showMsg("用户名或密码错误","index");
				//$this->error('用户名或密码错误!');
			}  
			 
			Db::name('sys_admin')->where('id', $admin['id'])->update(['last_login_time' => time()]);
			
			if(input("autoFlag"))
            {
                setcookie("adminID",$admin['id'],time()+7*24*3600);
                setcookie("adminName",$admin['admin_name'],time()+7*24*3600);
            }

            session('admin', $admin);
			//!empty($user['authorize']) && NodeService::applyAuthNode();
			//LogService::write('系统管理', '用户登录系统成功');
			$this->success('登录成功，正在进入系统...', 'index/index');
		}
	}
	
	public function login()
	{
		 $this->assign("title","后台管理");
		 $this->assign("adminName",$this->admin['admin_name']);
		 return $this->fetch();
	}
	
	public function logout()
	{

		session('admin', null);
    
    	if(cookie(session_name()))
    	{
        	cookie(session_name(),null);
    	}
    
    	if (cookie('adminID'))
    	{
        	cookie('adminID',null);
    	}
    
    	if (cookie('adminName'))
    	{
        	cookie('adminName',null);
    	}
    
		//LogService::write('系统管理', '用户退出系统成功');
		
		session_destroy();
		$this->success('退出登录成功！', 'index');
	}
}